package com.us.usws.support.filter;

import java.io.IOException;
import java.util.HashSet;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.us.usws.common.SiteConstants;
import com.us.usws.site.console.action.SysUserManagerAction;

/**
 * check admin is or not login
 * @author fengyong
 *
 */
public class CheckLoginFilter implements Filter {

	private static Log log = LogFactory.getFactory().getInstance(SysUserManagerAction.class);

	private HashSet<String> ignoreURI;
	private String appPath = "";

	@Override
	public void destroy() {

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpServletResponse httpResponse = (HttpServletResponse) response;

		HttpSession session = httpRequest.getSession();

		if (session.getAttribute(SiteConstants.SESSION_KEY_LOGIN_USER) == null) {
			String uri = httpRequest.getRequestURI();
			if (!uri.endsWith(".action") && !uri.endsWith(".jsp") && !uri.endsWith("/")) {
				chain.doFilter(request, response);
				return;
			} else {
				if (!ignoreURI.contains(uri)) {
					httpResponse.sendRedirect(appPath + "/login.jsp");
					log.info("if not login,then not access " + uri);
					return;
				}
			}
		}
		chain.doFilter(request, response);
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		appPath = filterConfig.getServletContext().getContextPath();
		ignoreURI = new HashSet<String>();
		ignoreURI.add(appPath + "/login.jsp");
		ignoreURI.add(appPath + "/ajaxLogin.action");
		ignoreURI.add(appPath + "/ajaxCheckIsLogin.action");
		ignoreURI.add(appPath + "/ajaxLogout.action");
	}
}
